package data

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"

	"rosesservice/internal/biz"

	"github.com/go-kratos/kratos/v2/log"
)

const NEWSKEY = "newsList"

type newsRepo struct {
	data *Data
	log  *log.Helper
}

func NewnewsRepo(data *Data, logger log.Logger) biz.NewsRepo {
	return &newsRepo{
		data: data,
		log:  log.NewHelper(logger),
	}
}

func (r *newsRepo) CreateNews(ctx context.Context, n *biz.News) (error, int) {
	// 先存数据库
	result := r.data.db.Create(n)
	// 再存一份到redis中
	newsJson, _ := json.Marshal(n)
	err := r.data.rdb.RPush(ctx, NEWSKEY, string(newsJson)).Err()
	if err != nil {
		// 日志
		log.Fatalf("redis RPush failed: %s", err)
		return nil, n.Id
	}
	return result.Error, n.Id
}

func (r *newsRepo) GetNews(ctx context.Context, newsId int) (error, *biz.News) {
	var news *biz.News
	result := r.data.db.Model(biz.News{Id: newsId}).Scan(&news)
	return result.Error, news
}

func (r *newsRepo) GetListNews(ctx context.Context, page, pageSize int) (error, []*biz.News) {
	newsList := make([]*biz.News, 0)

	// 分页参数
	startIndex := (page - 1) * pageSize
	endIndex := startIndex + pageSize - 1

	// 从redis中读数据
	result, err := r.data.rdb.LRange(ctx, NEWSKEY, int64(startIndex), int64(endIndex)).Result()
	if err != nil {
		// redis中没有数据然后从mysql中读
		res := r.data.db.Offset(startIndex).Limit(pageSize).Find(&newsList)
		return res.Error, newsList
	}
	// 解析redis中得数据
	var news *biz.News
	for _, item := range result {
		fmt.Println(item)
		err := json.Unmarshal([]byte(item), &news)
		if err != nil {
			log.Fatalf("JSON Unmarshalling failed: %s", err)
			return errors.New("JSON Unmarshalling failed"), newsList
		}
		newsList = append(newsList, news)
	}
	return nil, newsList
}
